package com.px.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.px.state.Px2VhState;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Px2VhAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Editor editor = e.getRequiredData(com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR);
        Document document = editor.getDocument();
        Px2VhState state = ServiceManager.getService(Px2VhState.class);
        final float designWidth = Float.valueOf(state.getHeight());
        WriteCommandAction.runWriteCommandAction(e.getProject(), () -> {
            String text = document.getText();
            Pattern pattern = Pattern.compile("(\\d+)px");
            Matcher matcher = pattern.matcher(text);
            StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                float pxValue = Float.parseFloat(matcher.group(1));
                float vhValue = (pxValue / designWidth) * 100;
                matcher.appendReplacement(sb, String.format("%.2fvh", vhValue));
            }
            matcher.appendTail(sb);
            document.setText(sb.toString());
        });
    }
}
